import router from './router'
import store from './store'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import { getToken } from '@/utils/auth' // get token from cookie
import layout from '@/layout/index'
import getPageTitle from '@/utils/get-page-title'
NProgress.configure({ showSpinner: false }) // NProgress Configuration

const whiteList = [
  '/login',
  //二维码内嵌页面
  '/login_code',
  '/home',
  '/testPage'
]

router.beforeEach(async (to, from, next) => {
  NProgress.start()
  const hasToken = getToken()
  // if (whiteList.includes(to.path)) {
  if (hasToken) {
    //只有第一次登陆需要动态路由
    if (!store.state.login.flag) {
      store.commit('login/CHANGE_FLAG', true)
      const routes = store.state.login.routes
      const filterRouter = filterAsyncRoute(routes)
      filterRouter.push({ path: '*', redirect: '/404', hidden: true })
      const roles = store.state.login.menuPermissionList
      let routerList
      if(!roles.includes('management')){
        routerList = filterRouter.filter(item=>{
          const currentName = item.type
          return currentName != 'management'
        })
      }else{
        routerList = filterRouter
      }
      router.addRoutes(routerList)
      store.commit('menu/SET_MMENULIST', routerList)
      next({
        ...to,
        replace: true
      })
    }
    next()
  } else {
    //未登录 是否去白名单页面
    if (whiteList.includes(to.path)) {
      next()
    } else {
      next('/login')
      NProgress.done()
    }
  }
}
)

router.afterEach((to) => {
  document.title = getPageTitle(to.meta.title)
  NProgress.done()
})


function filterAsyncRoute(asyncRouterMap) {
  return asyncRouterMap.map((route) => {
    if (route.component == "Layout") {
      route.component = layout
    }
    if (route.children && route.children.length) {
      route.children = filterAsyncRoute(route.children)
    } else {
      route.component = loadView(route.component)
    }
    return route
  })
}

function loadView(view) {
  return (resolve) => require([`@/${view}.vue`], resolve)
  // return () => import(`@/${view}.vue`)
}